﻿using System;
using System.Collections.Generic;

namespace lucere.io.concurrency
{
	public class SingleInstanceLock : Lock
	{
		private readonly HashSet<string> _locks;
		private readonly string _lockName;

		public SingleInstanceLock(HashSet<string> locks, string lockName)
		{
			_locks = locks;
			_lockName = lockName;
		}

		/// <summary>
		/// Attempts to obtain exclusive access and immediately return
		/// upon success or failure.
		/// </summary>
		/// <returns>true iff exclusive access is obtained</returns>
		public override bool Obtain()
		{
			lock (_locks)
			{
				return _locks.Add(_lockName);
			}
		}

		/// <summary>
		/// Releases exclusive access.
		/// </summary>
		public override void Release()
		{
			lock (_locks)
			{
				_locks.Remove(_lockName);
			}
		}

		/// <summary>
		/// Returns true if the resource is currently locked.  Note that one must
		/// still call <see cref="ILock.Obtain()"/> before using the resource.
		/// </summary>
		/// <returns></returns>
		public override bool IsLocked()
		{
			lock (_locks)
			{
				return _locks.Contains(_lockName);
			}
		}

		public override String ToString()
		{
			return base.ToString() + ": " + _lockName;
		}
	}
}